<?php
class PostsController extends AppController {

    public $name = 'Posts';
    public $helpers = array('Number','Media.Medium', 'Tagging.Tagging');
    public $cacheAction = array('view/' => '3 hour');
    protected $searchable = array(
        'created' => null,
        'created_by' => null,
        'modified' => null,
        'modified_by' => null,
        'post_term_id' => null,
        'title' => null,
    );
    public $paginate = array(
        'order' => 'Post.created DESC',
        'contain' => array(
            'PostTerm' => array('id', 'name', 'post_count'),
            'CreatedUser' => array('id', 'username'),
            'ModifiedUser' => array('id', 'username'),
        )
    );

    public function beforeFilter(){
        parent::beforeFilter();
        $this->Auth->allow('view','download', 'calendar');
        $this->_setCKFinderPath();
    }

    public function index(){
        $this->_justifyPaginator();
        $this->set('posts', $this->paginate());
    }

    public function view($id = null){
        if(!$id){
            $this->Session->setFlash(__('Invalid Post.', true));
            $this->redirect(array('action'=>'index'));
        }
        $this->Post->click($id);
        $this->set('post', $this->Post->getViewedPost($id));
    }

    public function add(){
        if(!empty($this->data)){
            $this->Post->create();
            if($this->Post->save($this->data)){
                $this->Event->dispatch('afterPostAdd', array(
                    'user' => $this->user,
                    'title' => $this->data['Post']['title'],
                    'id' => $this->Post->getLastInsertId()
                ));
                $this->Session->setFlash(__('The Post has been saved', true));
                $this->redirect(array('action'=>'edit', $this->Post->getLastInsertId()));
            } else {
                $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));
            }
        }
        $clouds = $this->Post->tagCloud();
        $postTerms = $this->Post->PostTerm->find('list');
        $this->set(compact('clouds', 'postTerms'));
    }

    public function edit($id = null){
        if(!$id && empty($this->data)){
            $this->Session->setFlash(__('Invalid Post', true));
            $this->redirect(array('action'=>'index'));
        }
        if(!empty($this->data)){
            //debug($this->data);
            $this->Post->saveAll($this->data, array('validate'=>'first'));
            /* clear view caches when update posts */
            clearCache();
            $this->Event->dispatch('afterPostEdit', array(
                'user' => $this->user,
                'title' => $this->data['Post']['title'],
                'id' => $id
            ));
            $this->Session->setFlash(__('The Post has been saved', true));
            $this->redirect(array('action'=>'index'));
        }
        if(empty($this->data)){
            $this->Post->recursive = 1;
            $this->data = $this->Post->read(null, $id);
            /* Redirect to index page when the current post is not written by current user*/
            if(($this->user['group'] == 'teacher') && ($this->user['id'] != $this->data['Post']['user_id'])){
                $this->Session->setFlash(__('You cannot edit post that is not written by youself', true));
                $this->redirect(array('action'=>'index'));
            }
        }
        $clouds = $this->Post->tagCloud();
        $postTerms = $this->Post->PostTerm->find('list');
        $this->set(compact('postTerms','id', 'clouds'));
    }

    public function delete($id = null){
        if(!$id){
            $this->Response->json(false, __('Invalid id for Post', true));
        }else{
            $this->Post->id = $id;
            if(($this->user['group'] == 'teacher') && ($this->user['id'] != $this->Post->field('user_id'))){
                $this->Response->json(false, __('You cannot delete post that is not written by youself', true));
            }elseif($this->Post->del($id)){
                $this->Response->json(true, __('Post deleted', true));
            }
        }
    }

    public function download($id=null){
        if(!$id){
            $this->Session->setFlash(__('Invalid Attachment', true));
            $this->redirect(array('action'=>'index'));
        }
        $attachment = $this->Post->getAttachment($id);
        // Redirect to home page if invalid attachment data returned
        if(!$attachment || empty($attachment['Attachment']['id'])){
            $this->Session->setFlash(__('Invalid Attachment', true));
            $this->redirect(array('action'=>'index'));
        }
        // Response with Component.Response.File
        $attachment = $attachment['Attachment'];
        $pieces = explode('.', $attachment['basename']);
        $extension = $pieces[count($pieces)-1];
        $params = array(
            'name'      => empty($attachment['alternative']) ? $attachment['basename'] : $attachment['alternative'],

            'size'      => $attachment['size'],
            'extension' => $extension,
            'file'      => MEDIA . $attachment['dirname'] . DS . $attachment['basename'],
            'mimeType'  => $attachment['mime_type']
        );
        $this->Response->file($params);
    }

    /* Search for posts with an specific keywords */
    public function search(){}

    /* Student page of posts, just like a blog */
    public function student(){
        $this->loadModel('PostTerm');
        $terms = $this->PostTerm->find('all', array(
            'order' => 'order ASC',
            'contain' => array(
                'Post' => array(
                    'conditions' => array('Post.published'=>1),
                    'order' => 'Post.created DESC',
                    'limit' => $this->options['postPageLimit']
                )
            )
        ));
        $hots = $this->Post->find('all', array(
            'fields' => array('id', 'title', 'clicks'),
            'order' => 'Post.clicks DESC',
            'limit' => $this->options['hotestPostLimit']
        ));
        $this->set(compact('terms', 'hots'));
    }

}
?>